import Vue from 'vue'
import VueRouter from 'vue-router'
import Layout from '@/components/Layout'
import Home from '../views/UnloggedView/Home.vue'
import PublishView from '../views/LoggedView/PublishView.vue'
import ProductDetail from '../views/UnloggedView/ProductDetail.vue'
import LoginView from '../views/UnloggedView/Login.vue'
import RegisterView from '../views/UnloggedView/RegisterView.vue'
import HomeRegisterView from '../views/LoggedView/HomeRegisterView.vue'
import UserView from '../views/LoggedView/UserView.vue'
import CategoryView from '../views/UnloggedView/Category.vue'
import OrderView from '../views/LoggedView/OrderView.vue'
import ProductsSearchView from '../views/UnloggedView/ProductsSearchView.vue'
import MessageView from '../views/LoggedView/MessageView.vue'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    component: Layout,
    children: [
      {
        path: '',
        name: 'Home',
        component: Home
      },
      {
        path: 'product/:id',
        name: 'ProductDetail',
        component: ProductDetail
      },
      {
        path: 'category/:id',
        name: 'Category',
        component: CategoryView
      },
      {
        path: 'search',
        name: 'Search',
        component: ProductsSearchView
      },
      {
        path: 'loggedhome',
        name: 'HomeRegister',
        component: HomeRegisterView,
        meta: { requiresAuth: true }
      },
      {
        path: 'user',
        name: 'UserView',
        component: UserView
      },
      {
        path: 'order',
        name: 'Order',
        component: OrderView,
        meta: { requiresAuth: true }
      },
      {
        path: 'message',
        name: 'Message',
        component: MessageView,
        meta: { requiresAuth: true }
      },
      {
        path: 'favorite',
        name: 'Favorite',
        component: () => import('@/views/LoggedView/FavoriteView.vue'),
        meta: { requiresAuth: true }
      },
      {
        path: 'history',
        name: 'History',
        component: () => import('@/views/LoggedView/HistoryView.vue'),
        meta: { requiresAuth: true }
      }
    ]
  },
  {
    path: '/publish',
    name: 'Publish',
    component: PublishView
  },
  {
    path: '/login',
    name: 'Login',
    component: LoginView
  },
  {
    path: '/register',
    name: 'Register',
    component: RegisterView
  }
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

// 添加全局路由守卫
router.beforeEach((to, from, next) => {
  const token = localStorage.getItem('token')
  const isLogged = localStorage.getItem('isLogged') === 'true'
  
  // 如果需要登录但未登录，重定向到登录页
  if (to.matched.some(record => record.meta.requiresAuth) && (!token || !isLogged)) {
    next({ name: 'Login' })
  } else {
    next()
  }
})

export default router
